package top.z.orm.handle.osql.dialect.mysql;

import top.z.orm.core.osql.dialect.DbFeature;
import top.z.orm.handle.osql.core.HoneyUtil;

import static top.z.orm.core.osql.SqlKeyWord.*;

public class MySqlFeature implements DbFeature {

    public String toPageSql(String sql, int start, int size) {
        // 去掉原来有的分号, 只能去掉最后一个
        // sql=sql.replace(";", "");
        sql = HoneyUtil.deleteLastSemicolon(sql);
        String    forUpdateClause = null;
        boolean   isForUpdate     = false;
        final int forUpdateIndex  = sql.toLowerCase().lastIndexOf(FOR_UPDATE);
        if (forUpdateIndex > -1) {
            forUpdateClause = sql.substring(forUpdateIndex);
            sql = sql.substring(0, forUpdateIndex - 1);
            isForUpdate = true;
        }
        String limitStament = "";
        if (HoneyUtil.isRegPagePlaceholder()) {
            int[] array = new int[2];
            // " limit ?,? "
            limitStament = SPACE + LIMIT + SPACE + QUESTION + COMMA + QUESTION + SPACE;
            array[0] = start;
            array[1] = size;
            HoneyUtil.regPageNumArray(array);
        } else {
            // limitStament = " limit " + start + "," + size;
            limitStament = " " + LIMIT + " " + start + "," + size;
        }
        sql += limitStament;
        if (isForUpdate) {
            sql += " " + forUpdateClause;
        }
        return sql;
    }

    public String toPageSql(String sql, int size) {
        return toPageSql(sql, 0, size);
    }
}